<template>
  <div class="step1">
    <header-bar tittle="发布任务"></header-bar>
    <div class="bg"></div>

    <div class="main">
      <div class="step-box">
        <div class="icon-box u-flex-center">
          <div class="icon">
            <van-image
              width="76rem"
              height="76rem"
              :src="require('@/assets/images/step1/icon_1@2x.png')"
            />
            <span>填写任务需求</span>
          </div>

          <div class="line"></div>

          <div class="icon">
            <van-image
              width="52rem"
              height="52rem"
              :src="require('@/assets/images/step1/icon_2@2x.png')"
            />
            <span>设置任务详情</span>
          </div>
        </div>
      </div>

      <div class="card">
        <div class="title">任务需求</div>

        <div class="form">
          <van-form @submit="onSubmit">
            <van-field
              class="border"
              readonly
              clickable
              label-align="left"
              style="font-size: 28rem"
              label-width="140rem"
              label="任务类型"
              :value="checkName"
              placeholder="请输入任务类型"
              @click="showPicker1 = true"
            />
            <van-popup v-model="showPicker1" round position="bottom">
              <van-picker
                title="任务类型"
                show-toolbar
                :columns="list"
                @cancel="showPicker1 = false"
                @confirm="onConfirm1"
              />
            </van-popup>
            <van-field
              class="border"
              label-align="left"
              label-width="140rem"
              v-model="name"
              type="text"
              size="large"
              name="name"
              label="任务名称"
              placeholder="请输入任务名称"
              :rules="getRule(name)"
              style="font-size: 28rem"
            />
            <van-field
              class="border"
              label-align="left"
              label-width="140rem"
              v-model="num"
              type="digit"
              size="large"
              name="num"
              label="任务单数"
              placeholder="请输入任务单数"
              :rules="[{ required: true, message: '请填写任务单数' }]"
              style="font-size: 28rem"
            />
            <van-field
              class="border"
              label-align="left"
              label-width="140rem"
              size="large"
              v-model="price"
              type="digit"
              name="price"
              label="任务价格"
              placeholder="请输入任务价格"
              :rules="[{ required: true, message: '请填写任务价格' }]"
              style="font-size: 28rem"
            />
            <van-field
              readonly
              clickable
              label-align="left"
              style="font-size: 28rem"
              label-width="140rem"
              label="有效时间"
              :value="value"
              placeholder="请选择有效时间"
              @click="showPicker = true"
              :rules="[{ required: true, message: '请选择有效时间' }]"
            />
            <van-popup v-model="showPicker" round position="bottom">
              <van-picker
                title="有效时间"
                show-toolbar
                :columns="columns"
                @cancel="showPicker = false"
                @confirm="onConfirm"
              />
            </van-popup>

            <!-- <van-button
              round
              block
              type="info"
              native-type="submit"
              @click="onSubmit"
              >下一步</van-button
            > -->
          </van-form>
        </div>
      </div>

      <div class="btn-box u-flex-center" @click="onSubmit">
        <div class="btn">下一步</div>
      </div>
    </div>
  </div>
</template>
<script>
import Vue from "vue";
import { Image as VanImage } from "vant";
import { TASK_PUBLISH, JOB_GET, MINE_MONNEY, ISSUE_BUY } from "@/api/api.js";
import header from "@/components/header/header.vue";
import {
  Picker,
  Tabbar,
  NoticeBar,
  Dialog,
  TabbarItem,
  Toast,
  Search,
  Swipe,
  SwipeItem,
  Grid,
  GridItem,
  Tab,
  Tabs,
  PullRefresh,
  List,
  Lazyload,
  Sticky,
  Step,
  Steps,
  Form,
} from "vant";
Vue.use(Tabbar);
Vue.use(TabbarItem);
Vue.use(Swipe);
Vue.use(Search);
Vue.use(SwipeItem);
Vue.use(Grid);
Vue.use(GridItem);
Vue.use(Tab);
Vue.use(Tabs);
Vue.use(PullRefresh);
Vue.use(List);
Vue.use(Lazyload);
Vue.use(Sticky);
Vue.use(VanImage);
Vue.use(NoticeBar);
Vue.use(Step);
Vue.use(Steps);
Vue.use(Form);
Vue.use(Picker);
Vue.use(Dialog);
Vue.use(Toast);

export default {
  name: "step1",
  components: {
    [Tabs.name]: Tabs,
    [Tab.name]: Tab,
    [header.name]: header,
  },
  data() {
    return {
      id: "",
      active: 0,
      name: "",
      num: "",
      price: "",
      // 选择类型下拉
      list: [],
      showPicker1: false,
      checkName: "",
      type_id: "",
      // 获取数据
      durationList: [],
      issueLevelList: [],
      balance: "",
      verify: "",
      issueRemainTimes: "",
      // 有效时间
      value: "",
      showPicker: false,
      columns: [],
      duration: "",
      // 等级判断
      show: false,
      radio: "",
      levelList: [],
      curLevel: "",
      amountsAll: "",
      needsAll: "",
      taskPrice: "",
      level: "",
    };
  },
  mounted() {
    this.getInitData();
    let id = this.$route.query.id;
    let checkName = this.$route.query.name;
    this.type_id = id;
    this.checkName = checkName;
    this.getKind();
  },
  methods: {
    // 校验
    // 	:rules="[{ required: true, message: '请填写任务名称' }]"
    getRule(index) {
      if (index == "") {
        return [
          { index, validator: this.validator, message: "请填写任务名称" },
        ];
      } else if (index.length < 3) {
        return [
          {
            index,
            validator: this.validator,
            message: "任务名称长度需大于3个字节",
          },
        ];
      }
    },
    validator(value, rule) {
      return false;
    },

    async getKind() {
      const { data } = await this.$reqGet(JOB_GET, {});
      if (data.status == 1) {
        let list = JSON.parse(JSON.stringify(data.data));
        let arr = [];
        for (let i = 0; i < list.length; i++) {
          for (let j = 0; j < list[i].sublist.length; j++) {
            arr.push({
              id: list[i].sublist[j]["id"],
              text: list[i].sublist[j]["name"],
            });
          }
        }
        let a = JSON.parse(JSON.stringify(arr));
        this.list = a;
      }
    },
    async getInitData() {
      const { data } = await this.$reqPost(TASK_PUBLISH, {});
      if (data.status == 1) {
        // this.columns = data.data.issueLevelList;
        let dateArr = [];
        dateArr = data.data.durationList;
        for (let i = 0; i < dateArr.length; i++) {
          dateArr[i]["text"] = dateArr[i]["value"];
        }

        this.columns = dateArr;
        this.verify = data.data.verify;
        this.balance = data.data.balance;
        this.issueRemainTimes = data.data.issueRemainTimes;
      }
    },
    onConfirm(value) {
      let val = JSON.parse(JSON.stringify(value));
      this.value = val.value;
      this.duration = val.key;
      // picker.setColumnValues(1,cities[values[0]]);
      this.showPicker = false;
    },
    onConfirm1(value) {
      let val = JSON.parse(JSON.stringify(value));
      this.checkName = val.text;
      this.type_id = val.id;
      // picker.setColumnValues(1,cities[values[0]]);
      this.showPicker1 = false;
    },
    // onChange(picker, values) {
    // 	picker.setColumnValues(1, cities[values[0]]);
    // },
    justifyImgWidth(e) {
      this.Imgheight = e.currentTarget.clientWidth;
      // this.logoWidth = e.currentTarget.clientHeight * 2.75
    },
    async getAmount() {
      const { data } = await this.$reqGet(MINE_MONNEY, {});
      if (data.status == 1) {
        let info = data.data;
        this.amountsAll =
          parseFloat(info.withdraw_amount) +
          parseFloat(info.non_withdraw_amount);
      }
    },
    async onSubmit(values) {
      this.getAmount();
      let datas = {
        balance: this.balance,
        verify: this.verify,
        type_id: this.type_id,
        name: this.name,
        num: Number(this.num),
        price: Number(this.price),
        duration: this.duration,
        total_amount: this.num * this.price,
      };
      // 判断是否充值需要
      let numberCom = values.num * values.price;
      let balance = this.balance;
      if (balance < numberCom) {
        Dialog.confirm({
          title: "提示",
          message: "余额不足,请前往充值！",
        })
          .then(() => {
            this.$router.push({ name: "wallet" });
          })
          .catch(() => {});
      }
      if (balance < numberCom) {
        return;
      }
      // 发布价格
      const { data } = await this.$reqPost(TASK_PUBLISH, {});

      if (data.status == 1) {
        let levelList = JSON.parse(JSON.stringify(data.data.issueLevelList));
        for (let i = 0; i < levelList.length; i++) {
          if (levelList[i].current == true && i < levelList.length - 1) {
            this.curLevel = i;
            let monney = levelList[i].amount;
            this.level = i + 1;
            let needsAll = levelList[i + 1].amount
              ? levelList[i + 1].amount
              : 0;
            this.needsAll = needsAll;
            this.radio = i + 1;
          }
        }

        this.levelList = levelList;
        let issueRemainTimes = data.data.issueRemainTimes;
        if (issueRemainTimes <= 0) {
          this.show = true;
        } else {
          console.log(datas);
          this.$router.push({
            name: "step2",
            query: { data: encodeURI(JSON.stringify(datas)) },
          });
        }
      }
    },
    // 选择分类
    checkLevel(index) {
      let list = this.levelList;
      this.level = index;
      let amounts = 0;
      for (let i = 0; i < list.length; i++) {
        if (list[i].current == true) {
          for (let k = i; k < index; k++) {
            amounts += list[k + 1].amount;
          }
        }
      }
      this.needsAll = parseFloat(amounts);
    },
    // 充值等级
    async levelget() {
      let oldid = this.curLevel + 1;
      let newid = this.levelList[this.level].level_id;
      let amount = this.needsAll;
      let datas = {
        current: oldid,
        buy: newid,
        amount: amount,
      };

      const { data } = await this.$reqPost(ISSUE_BUY, datas);
      if (data.status == 1) {
        Toast(data.info);
        this.show = false;
        this.getInitData();
      } else {
        Toast(data.info);
        this.show = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.step1 {
  min-height: 100vh;
  background-color: #f5f5f5;

  .bg {
    height: 464rem;
    background: linear-gradient(
      180deg,
      #2f81fe 80%,
      rgba(47, 129, 254, 0) 100%
    );
  }

  .main {
    position: relative;

    .step-box {
      align-items: flex-end;

      .line {
        width: 300rem;
        height: 8rem;
        background-color: #1968ff;
      }

      .icon-box {
        margin-top: 42rem;

        .icon {
          position: relative;
          span {
            position: absolute;
            font-size: 24rem;
            width: 144rem;
            left: 50%;
            transform: translate(-50%);
            bottom: -36rem;
            color: #fff;
          }

          &:nth-child(3) {
            span {
              bottom: -48rem;
              color: #1968ff;
            }
          }
        }
      }
    }

    .card {
      background-color: #fff;
      border-radius: 20rem;
      overflow: hidden;
      margin: 0 24rem;
      margin-top: 70rem;

      .title {
        padding-left: 24rem;
        font-weight: bold;
        font-size: 32rem;
        text-align: left;
        height: 92rem;
        background-color: #f3f7fe;
        line-height: 92rem;
      }

      .form {
        padding: 0 24rem;

        /deep/ .van-cell__title {
          font-size: 28rem;
          color: #66696e;

          span {
            &::after {
              content: "*";
              color: #ff4343;
              font-size: 28rem;
              margin-left: 8rem;
            }
          }
        }

        /deep/.van-cell {
          &:nth-child(1) {
            .van-cell__title {
              span {
                &::after {
                  content: "";
                  color: #ff4343;
                  font-size: 28rem;
                  margin-left: 8rem;
                }
              }
            }
          }
        }

        /deep/ .van-field__control {
          text-align: right;
        }

        /deep/ .van-field__error-message {
          text-align: right !important;
        }

        /deep/ .van-cell {
          padding: 24rem 0;
        }

        .border {
          border-bottom: 2rem solid #f8f8f8;
        }
      }
    }

    .btn-box {
      margin: 80rem 24rem 0;
      border-radius: 44rem;
      height: 88rem;
      background: linear-gradient(145deg, #2cb1ff 0%, #2f81fe 100%);
      font-size: 32rem;
      color: #fff;
      font-weight: bold;

      .btn {
        width: 100%;
      }
    }
  }
}
</style>
